package sam.learn.framework.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 1、精确地控制哪些用户可以访问哪些资源
 * 重写 configure(HttpSecurity http) 方法
 * http.authorizeRequests().antMatchers("/admin/**").anyRequest().authenticated().hasRole("ADMIN").and().formLogin();
 * 还可以设置跨域
 * http.cors().configurationSource((httpServletRequest) -> { return new CorsConfiguration(); });
 * 重写 configure(WebSecurity web) 方法 不进行认证的路径，可以直接访问
 * WebSecurity.IgnoredRequestConfigurer ignoredRequestConfigure = web.ignoring().antMatchers("/moped/**")
 * 2、对密码进行合适的加密处理
 * 允许你定义密码的加密方式
 * auth.userDetailsService(userDetailsService).passwordEncoder(defaultPasswordEncoder);
 * <p> HttpSecurity <p/>
 * HttpSecurity 是 Spring Security 中用于构建安全配置的一个类。
 * 通过该类，开发者可以配置许多与 HTTP 安全相关的选项，如认证、授权、CORS、CSRF 保护等。
 * 它提供了一种流畅的 DSL（领域特定语言），使得安全配置变得直观和易于理解。
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebMvcConfigurationSupport {

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private JwtRequestFilter jwtRequestFilter;


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http, BCryptPasswordEncoder bCryptPasswordEncoder, UserDetailsService userDetailService)
            throws Exception {
        return http.getSharedObject(AuthenticationManagerBuilder.class)
                .userDetailsService(userDetailService)
                .passwordEncoder(bCryptPasswordEncoder)
                .and()
                .build();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(
                        (auth) -> auth
                                .mvcMatchers("/login/**")
                                .permitAll()
                                .anyRequest()
                                .authenticated()
                )
                .exceptionHandling(exception -> exception.authenticationEntryPoint(jwtAuthenticationEntryPoint))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class)
                .httpBasic();

        return httpSecurity.build();
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring()
                .antMatchers("/css/**", "/js/**", "/img/**", "/lib/**","/demo/**", "/favicon.ico");
    }

}
